from django.shortcuts import render, redirect
from app01 import models
from app01.utils.pagination import Pagination

from app01.utils.form import UserModelForm,MobileModelForm,MobileeditModelForm

# Create your views here.
def depart_list(request):
    """部门列表"""

    #却数据库中获取部门信息
    queryset = models.Department.objects.all()
    ## 分页
    page_object = Pagination(request,queryset,page_size=2)
    context = {
         'queryset':page_object.page_queryset,
          'page_string':page_object.html(),
    }
    return render(request,'depart_list.html',context)


def depart_add(request):
    """添加部门"""
    if request.method == "GET":
        return render(request,'depart_add.html')
    # 获取用户通过post提交的是数据集
    title = request.POST.get("title")
    # 保存到数据库
    models.Department.objects.create(title=title)
    #重定项回部门列表
    return redirect("/depart/list/")

def depart_delete(request):
    """"删除部门"""
    # 获取id
    nid = request.GET.get('nid')
    # 删除
    models.Department.objects.filter(id=nid).delete()
    # 跳转
    return redirect("/depart/list/")

def depart_edit(request,nid):
    """编辑部门"""
    if request.method == "GET":
        #根据nid获取数据
        row_object = models.Department.objects.filter(id=nid).first()
        return render(request,'depart_edit.html',{'row_object':row_object})

    #获取用户提交的标题，根据id找到数据库中的数据并进行更新
    models.Department.objects.filter(id=nid).update(title=request.POST.get("title"))

    #重新定向会部门列表
    return redirect("/depart/list/")